package com.demo.auth.service;

import com.demo.auth.config.OauthProperties;
import com.demo.auth.constant.UserDetailsServiceName;
import com.demo.auth.dao.domain.User;
import com.demo.auth.dao.mapper.UserMapper;
import com.demo.auth.dao.service.UserService;
import com.demo.auth.entity.AdminUserDetails;
import com.demo.common.constants.AuthModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 获取用户信息
 */
@Slf4j
@Service(UserDetailsServiceName.ADMIN)
public class AuthUserDetailService implements UserDetailsService {

    @Resource
    private UserService userService;
    @Resource
    private OauthProperties oauthProperties;
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("AdminUserServiceImpl：{}", username);
        User user = userService.getById(username);

        List<Long> roleIds = userMapper.getRoleIdByUserId(user.getId());
        String authorityString = roleIds.stream().map(Object::toString).distinct().collect(Collectors.joining(","));
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(authorityString);
        String password = oauthProperties.getPasswordEncode() + user.getPassword();

        return new AdminUserDetails(user.getId(),  user.getUserName(), password, AuthModel.USERNAME_PASSWORD, authorityList);
    }
}
